/*=========================================================================

  Library:   HMP

  Copyright (c) Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=========================================================================*/

// Qt includes
#include <QDebug>

// HMP includes
#include <Logger.h>
#include <QTextStream>
#include <QFile>
#include <QDir>
#include <QDateTime>
#include <QApplication>

// Log4Qt includes
//#include <log4qt/log4qt.h>
//#include <log4qt/logger.h>
//#include <log4qt/basicconfigurator.h>

//-----------------------------------------------------------------------------

#define LogDir qApp->applicationDirPath()+"/./../logs"
#define ONEHOUR 60*60
#define _1M 1024*1024

class baseLogger
{
public:

    baseLogger(const QString &filename){

        start = QDateTime::currentDateTime();
        mkdir();
        m_filename += LogDir+"/"+filename;
        openfile();
    }

	virtual ~baseLogger(){
		m_file.close();
	}

    void log(const QString &text){
        mkfile();
        QDateTime cur = QDateTime::currentDateTime();
        QString log = cur.toString("yyyy:MM:dd hh:mm:ss") +"::"+text +"\r\n";
        m_file.write(log.toLocal8Bit());

    }

protected:
    void openfile(){
        m_file.setFileName(m_filename);
        bool ret = m_file.open(QIODevice::WriteOnly|QIODevice::Append);
		if (!ret) qWarning()<<"open file error";
		
    }

    void mkdir(){
        QDir dir;
        if(!dir.exists(LogDir)){
            dir.mkdir(LogDir);
        }
    }
    void mkfile(){
        QDateTime cur = QDateTime::currentDateTime();

        if((cur.secsTo(start) > ONEHOUR*2) || (m_file.size() > _1M*10)){
            QString filename = m_file.fileName();
            filename += cur.toString(".yyyy_MM_dd-hh_mm_ss");
            m_file.rename(filename);
            openfile();
            start = QDateTime::currentDateTime();
        }
    }

private:
    baseLogger(){}

private:
    QDateTime start;
    QFile m_file;
    QString m_filename;
};

#define MakeLogger(ClassName,FileName) \
class ClassName##Logger:public baseLogger\
{\
public:\
    static baseLogger* Instance()\
    {\
        static ClassName##Logger logger(FileName);\
        return &logger;\
    }\
\
private:\
    ClassName##Logger(const QString &filename):baseLogger(filename){}\
\
};\

MakeLogger(Fatal,"Fatal.log")
MakeLogger(Critical,"Critical.log")
MakeLogger(Error,"Error.log")
MakeLogger(Warn,"Warn.log")
MakeLogger(Notice,"Notice.log")
MakeLogger(Info,"Info.log")

#define Factory(Name) Name##Logger::Instance();

class LoggerFactory
{
public:
    enum LogType{
        FATAL,
        CRITICAL,
        ERROR,
        WARN,
        NOTICE,
        INFO
    };

    static baseLogger *getLoger(LogType type)
    {
        switch (type) {
        case FATAL:
            return Factory(Fatal)
            break;
        case CRITICAL:
            return Factory(Critical)
            break;
        case ERROR:
            return Factory(Error)
            break;
        case WARN:
            return Factory(Warn)
            break;
        case NOTICE:
            return Factory(Notice)
            break;
        case INFO:
            return Factory(Info)
            break;
        default:
            return nullptr;
            break;
        }
    }

};

#define _FATAL(x) LoggerFactory::getLoger(LoggerFactory::FATAL)->log(x);
#define _CRITICAL(x) LoggerFactory::getLoger(LoggerFactory::CRITICAL)->log(x);
#define _ERROR(x) LoggerFactory::getLoger(LoggerFactory::ERROR)->log(x);
#define _WARN(x) LoggerFactory::getLoger(LoggerFactory::WARN)->log(x);
#define _NOTICE(x) LoggerFactory::getLoger(LoggerFactory::NOTICE)->log(x);
#define _INFO(x) LoggerFactory::getLoger(LoggerFactory::INFO)->log(x);

class LoggerPrivate
{
public:
  //Log4Qt::Logger *Logger;
};

//-----------------------------------------------------------------------------
Logger::Logger(QObject* _parent)
  : Superclass(_parent)
  , d_ptr(new LoggerPrivate)
{
}

//-----------------------------------------------------------------------------
Logger *Logger::GetInstance()
{
    static Logger inst;
    return &inst;
}

Logger::~Logger()
{
}

//-----------------------------------------------------------------------------
void Logger::debug(const char* msg)
{
  //Q_D(Logger);
  //d->Logger->debug(s);
  _INFO(msg)
  qDebug().nospace() << qPrintable(msg);
}

//-----------------------------------------------------------------------------
void Logger::info(const char *msg)
{
  //Q_D(Logger);
  //d->Logger->info(s);
  _INFO(msg)
  qDebug().nospace() << qPrintable(msg);
}

//-----------------------------------------------------------------------------
void Logger::notice(const char *msg)
{
  //Q_D(Logger);
  //d->Logger->trace(s);
  _NOTICE(msg)
  qDebug().nospace() << qPrintable(msg);
}

//-----------------------------------------------------------------------------
void Logger::warning(const char *msg)
{
  //Q_D(Logger);
  //d->Logger->warn(s);
  _WARN(msg)
  qWarning().nospace() << qPrintable(msg);
}

//-----------------------------------------------------------------------------
void Logger::error(const char *msg)
{
  //Q_D(Logger);
  //d->Logger->error(s);
    _ERROR(msg)
    qCritical().nospace() << qPrintable(msg);
}

void Logger::critical(const char *msg)
{
    _CRITICAL(msg)
    qCritical().nospace() << qPrintable(msg);
}

//-----------------------------------------------------------------------------
void Logger::fatal(const char *msg)
{
  //Q_D(Logger);
  //d->Logger->fatal(s);
  _FATAL(msg)
          qCritical().nospace() << qPrintable(msg);
}

void Logger::information(const char *msg)
{
    _INFO(msg)
    qDebug().nospace()<<qPrintable(msg);
}

////-----------------------------------------------------------------------------
//void Logger::setOff()
//{
//  //Q_D(Logger);
//  //d->Logger->setLevel(Log4Qt::Level(Log4Qt::Level::OFF_INT));
//}

////-----------------------------------------------------------------------------
//void Logger::setDebug()
//{
//  //Q_D(Logger);
//  //d->Logger->setLevel(Log4Qt::Level(Log4Qt::Level::DEBUG_INT));
//}

////-----------------------------------------------------------------------------
//void Logger::setInfo()
//{
//  //Q_D(Logger);
//  //d->Logger->setLevel(Log4Qt::Level(Log4Qt::Level::INFO_INT));
//}

////-----------------------------------------------------------------------------
//void Logger::setTrace()
//{
//  //Q_D(Logger);
//  //d->Logger->setLevel(Log4Qt::Level(Log4Qt::Level::TRACE_INT));
//}

////-----------------------------------------------------------------------------
//void Logger::setWarn()
//{
//  //Q_D(Logger);
//  //d->Logger->setLevel(Log4Qt::Level(Log4Qt::Level::WARN_INT));
//}

////-----------------------------------------------------------------------------
//void Logger::setError()
//{
//  //Q_D(Logger);
//  //d->Logger->setLevel(Log4Qt::Level(Log4Qt::Level::ERROR_INT));
//}

////-----------------------------------------------------------------------------
//void Logger::setFatal()
//{
//  //Q_D(Logger);
//  //d->Logger->setLevel(Log4Qt::Level(Log4Qt::Level::FATAL_INT));
//}

////-----------------------------------------------------------------------------
//bool Logger::isOffEnabled()
//{
//  //Q_D(Logger); //Not sure
//  //return d->Logger->isEnabledFor(Log4Qt::Level(Log4Qt::Level::OFF_INT));
//}

////-----------------------------------------------------------------------------
//bool Logger::isDebugEnabled()
//{
//  //Q_D(Logger);
//  //return d->Logger->isDebugEnabled();
//}

////-----------------------------------------------------------------------------
//bool Logger::isInfoEnabled()
//{
//  //Q_D(Logger);
//  //return d->Logger->isInfoEnabled();
//}

////-----------------------------------------------------------------------------
//bool Logger::isTraceEnabled()
//{
//  //Q_D(Logger);
//  //return d->Logger->isTraceEnabled();
//}

////-----------------------------------------------------------------------------
//bool Logger::isWarnEnabled()
//{
//  //Q_D(Logger);
//  //return d->Logger->isWarnEnabled();
//}

////-----------------------------------------------------------------------------
//bool Logger::isErrorEnabled()
//{
//  //Q_D(Logger);
//  //return d->Logger->isErrorEnabled();
//}

////-----------------------------------------------------------------------------
//bool Logger::isFatalEnabled()
//{
//  //Q_D(Logger);
//  //return d->Logger->isFatalEnabled();
//}
